package com.jonesun.test.javafx;

import javafx.application.Preloader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.ProgressBar;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

import java.util.Arrays;
import java.util.Collection;

/**
 * @author jone.sun
 * @version 1.0
 * @date 2020/5/14 15:04
 */
public class AppPreloader extends Preloader {

    private Stage stage;

    @Override
    public void start(Stage primaryStage) throws Exception {
        this.stage = primaryStage;
        final Scene splashScene = new Scene(getParent(), Color.TRANSPARENT);
        primaryStage.initStyle(StageStyle.TRANSPARENT);
        primaryStage.setScene(splashScene);
        primaryStage.getIcons().addAll( loadDefaultIcons());
        primaryStage.show();
    }

    public Parent getParent() {
        final ImageView imageView = new ImageView(getClass().getResource("/splash/javafx.png").toExternalForm());
        final ProgressBar splashProgressBar = new ProgressBar();
        splashProgressBar.setPrefWidth(imageView.getImage().getWidth());

        final VBox vbox = new VBox();
        vbox.getChildren().addAll(imageView, splashProgressBar);

        return vbox;
    }

    @Override
    public void handleProgressNotification(ProgressNotification info) {
        System.out.println("handleProgressNotification=" + info.getProgress());
    }


    /**
     * 重载这个方法可以处理应用通知
     *
     * @param info
     */
    @Override
    public void handleApplicationNotification(PreloaderNotification info) {
        if (info instanceof ProgressNotification) {
            //提取应用程序发送过来的进度值
            double v = ((ProgressNotification) info).getProgress();
            System.out.println("handleApplicationNotification=" + v);
        } else if (info instanceof StateChangeNotification) {
            //隐藏/或者关闭preloader
//            stage.hide();
            stage.close();
        }
    }

    public Collection<Image> loadDefaultIcons() {
        return Arrays.asList(new Image(getClass().getResource("/icons/gear_16x16.png").toExternalForm()),
                new Image(getClass().getResource("/icons/gear_24x24.png").toExternalForm()),
                new Image(getClass().getResource("/icons/gear_36x36.png").toExternalForm()),
                new Image(getClass().getResource("/icons/gear_42x42.png").toExternalForm()),
                new Image(getClass().getResource("/icons/gear_64x64.png").toExternalForm()));
    }



}
